import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/indexView'
import Layout from '@/views/layout/indexView'
import Home from '@/views/Home/indexView'
import User from '@/views/User/indexView'
// import Search from '@/views/Search/indexView'
// import SearchResult from '@/views/Search/SearchResult'
// import ArticleDetail from '@/views/ArticleDetail/indexView'
// import UserEdit from '@/views/User/UserEdit'
// import Chat from '@/views/Chat/indexView'
import { getToken } from '@/utils/token.js'

Vue.use(VueRouter)

const routes = [
  // 访问根路径，重定向到首页
  {
    path: '/',
    redirect: '/layout/home'
  },
  // 登录页面路由
  {
    path: '/login',
    component: Login,
    // 独享路由守卫，如果已登录，不能通过路由跳转到登录页面
    beforeEnter (to, from, next) {
      // vuex里有token(代表登录过, 但是一定要注意过期和主动退出要先清除vuex和本地的token, 让其跳转登录页)
      if (getToken()?.length > 0) {
        next(false) // 如果有token，则不能放行
      } else {
        next() // 说明没有token，放行
      }
    }
  },
  // layout路由，作为首页和我的页面的一级路由
  {
    path: '/layout',
    component: Layout,
    // layout的子路由
    children: [
      // 首页路由
      {
        path: 'home',
        component: Home
      },
      // 我的路由
      {
        path: 'user',
        component: User
      }
    ]
  },
  // 文章搜索页路由
  {
    path: '/search',
    component: () => import('@/views/Search/indexView')
  },
  // 搜索结果页路由
  {
    path: '/search_result/:kw',
    component: () => import('@/views/Search/SearchResult')
  },
  // 文章详情页路由
  {
    path: '/detail',
    component: () => import('@/views/ArticleDetail/indexView')
  },
  // 用户编辑页面路由
  {
    path: '/user_edit',
    component: () => import('@/views/User/UserEdit')
  },
  // 聊天页面路由
  {
    path: '/chat',
    component: () => import('@/views/Chat/indexView')
  }
]

const router = new VueRouter({ routes })

// 全局路由前置守卫，在跳转路由之前，执行次函数
// router.beforeEach((to, from, next) => {
//   // 需求：如果你已经登录了，不要切换到登录页面
//   if (getToken()?.length > 0 && to.path === '/login') {
//     next(false) // 留在原地
//   } else {
//     next() // 其他情况通通放行
//   }
// }
// )
// 解决报错
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
// push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
// replace
VueRouter.prototype.replace = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}
export default router
